/* Includes ---------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "main.h"
#include "user_init.h"
#include "fm33_assert.h"
#include "uart.h"
#include "ADS1220.h"
#include "DAC_SGM5353.h"
#include "hart_handler.h"
#include "DataFlashMap.h"
/* USER CODE END Includes */

/* Types ------------------------------------------------------------*/
/* USER CODE BEGIN Types */

/* USER CODE END Types */

/* Constants --------------------------------------------------------*/
/* USER CODE BEGIN Constants */

/* USER CODE END Constants */

/* Macro ------------------------------------------------------------*/
/* USER CODE BEGIN Macro */

/* USER CODE END Macro */

/* Variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */
uint16_t guiSysFlag = 0;
/* USER CODE END Variables */

/* Function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FP */
void vCmdHandler(void);
/* USER CODE END FP */

uint32_t adc = 0;
float mv = 0.0f;

int main(void)
{
    /* Initialize FL Driver Library */
    FL_Init();

    /* Configure the system clock */
    MF_Clock_Init();

    /* Initialize all configured peripherals */
    MF_Config_Init();
	
	vADS1220Reset();
	
	vDataFlashPowerOnLoadData();
	
	//IWDT_Init();
	
	//uint8_t data[2] = {0x01, 0x23};
	uint32_t cnt = 0;
	
	vDACSGM5353OutputMV(0x3E8);

    while(1)
    {
		//FL_IWDT_ReloadCounter(IWDT);
		
		vCmdHandler();
		
		vHartHandler();
		
		cnt = 0xffff;
		while(cnt--);
		
		//vUartTxData(data, 2);
		//adc = ulADS1220GetADCDataAverage();
		
		//adc = ulADS1220GetADCDataMedian();
		//mv = (double)adc / 8388608.0 * 0.5 / 128.0 * 1000.0;
		//printf("signal: %f(mV)\r\n", mv);
		
//		FL_GPIO_ToggleOutputPin(GPIOB, FL_GPIO_PIN_12);
//		FL_GPIO_ToggleOutputPin(GPIOD, FL_GPIO_PIN_0);
//		FL_GPIO_ToggleOutputPin(GPIOD, FL_GPIO_PIN_1);
    }
}

void vCmdHandler(void)
{
	if(GET_UART4_RX_FINISHED_FLG())
	{
		uint16_t uiDAVal;
		
		if(stUart4Rx.ucAryBuffer[0] == 0xA5)
		{
			switch(stUart4Rx.ucAryBuffer[1])
			{
				case 0x01:
					FL_PMU_SetLowPowerMode(PMU, FL_PMU_POWER_MODE_LPRUN_ONLY);
					break;
				
				case 0x02:
					FL_PMU_SetLowPowerMode(PMU, FL_PMU_POWER_MODE_ACTIVE_OR_LPACTIVE);
					break;
				
				case 0x03:
					uiDAVal = (((uint16_t)stUart4Rx.ucAryBuffer[2]) << 8) + stUart4Rx.ucAryBuffer[3];
					vDACSGM5353OutputMV(uiDAVal);
					break;
				
				default:
					break;
			}
		}
		vUart4RxBufferClr();
		CLR_UART4_RX_FINISHED_FLG();
	}
}

void IWDT_Init(void)
{
    FL_IWDT_InitTypeDef    IWDT_InitStruct;

    IWDT_InitStruct.iwdtWindows = 0;
    IWDT_InitStruct.overflowPeriod = FL_IWDT_PERIOD_2000MS;

    FL_IWDT_Init(IWDT, &IWDT_InitStruct);
}


